package com.lwgk.compsql;

import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.lwgk.AppComplication;
import com.lwgk.DaoMaster;
import com.lwgk.DaoSession;
import com.lwgk.UserSpSaveDao;
import com.lwgk.constant.ConstantUtils;
import com.lwgk.encryption.DesSecreat;

import org.greenrobot.greendao.query.QueryBuilder;
import java.util.List;

/**
 * created by 赵航
 * 联系微信 微信号：zhao--hang--
 * on 2019/7/19
 * --------------------------------------------------------------------------
 * 描述：已经封装完成的高仿Sp保存类，存在手机内部，并未存放到sdk
 * 注意事项：保存的全部都是字符串，其中包含加密和解密成分
 */
public class UserSpSaveManager {
    private static UserSpSaveManager mUserSpSaveManager;
    private        UserSpSaveDao     mUserDaoDao;
    private        DaoSession        mDaoSession;
    /**
     * 私有构造方法
     */
    private UserSpSaveManager() {
        // 初始化数据库信息
        DaoMaster.DevOpenHelper mDevOpenHelper = new DaoMaster.DevOpenHelper(AppComplication.mContext, ConstantUtils.SQLSPNAME, null);
        // MyDaoMaster mDevOpenHelper = new MyDaoMaster(AppComplication.mContext, ConstantUtils.SQLSPNAME, null);//数据库导表，升级专用
        SQLiteDatabase db = mDevOpenHelper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        mDaoSession = daoMaster.newSession();
        mUserDaoDao = mDaoSession.getUserSpSaveDao();
    }
    /**
     * @return 设置单例模式
     */
    public static UserSpSaveManager getInstance() {
        if (null == mUserSpSaveManager) {
            synchronized (UserSpSaveManager.class) {
                if (null == mUserSpSaveManager) {
                    mUserSpSaveManager = new UserSpSaveManager();
                }
            }
        }
        return mUserSpSaveManager;
    }
    /**
     * 保存数据
     */
    public void setSaveData(String key, String value) {
        if (mUserSpSaveManager == null) {
            getInstance();
        }
        //加密保存
        String newValue = DesSecreat.getInstance().encryptPassword(value);
        UserSpSave userSpSave = new UserSpSave(System.currentTimeMillis(), key, newValue);
        mUserDaoDao.insertOrReplace(userSpSave);
    }
    /**
     * 读取数据
     */
    public String getSaveData(String key) {
        if (mUserSpSaveManager == null) {
            getInstance();
        }

        QueryBuilder<UserSpSave> qb = mDaoSession.queryBuilder(UserSpSave.class);
        //根基条件查询
        QueryBuilder<UserSpSave> studentQueryBuilder = qb.where(UserSpSaveDao.Properties.Key.eq(key));
        List<UserSpSave> studentList = studentQueryBuilder.list();
        if (studentList.size()==0){
            return "";
        }else {
            //解密读取
            return  DesSecreat.getInstance().decryptPassword(studentList.get(0).getValue());
        }
    }
}
